// src/main/java/com/cupk/controllers/FundingController.java (最终正确版)

package com.cupk.controllers;

import com.cupk.dtos.*;
import com.cupk.services.FundingService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/fundings")
@RequiredArgsConstructor
public class FundingController {

    private final FundingService fundingService;

    /**
     * 创建经费记录
     */
    @PostMapping
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<FundingDto> createFunding(@Valid @RequestBody CreateFundingRequest request, Authentication authentication) {
        FundingDto createdFunding = fundingService.createFunding(request, authentication.getName());
        return new ResponseEntity<>(createdFunding, HttpStatus.CREATED);
    }

    /**
     * 【已修正】
     * 获取经费记录列表，支持多种筛选条件。
     * 这是处理 GET /fundings 的唯一方法。
     */
    @GetMapping
    @PreAuthorize("isAuthenticated()") // 【已添加】确保此接口受保护
    public ResponseEntity<List<FundingDto>> getAllFundings(
            @RequestParam(required = false) Long projectId,
            @RequestParam(required = false) String fundingType,
            @RequestParam(required = false) String approvalStatus,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String keyword
    ) {
        // 调用 Service 层中那个支持所有参数的方法
        List<FundingDto> fundings = fundingService.getAllFundings(
                projectId, fundingType, approvalStatus, startDate, endDate, keyword
        );
        return ResponseEntity.ok(fundings);
    }

    // 【已删除】旧的、无参数的 getAllFundings 方法已被移除，以解决映射冲突

    /**
     * 根据项目ID获取经费记录
     */
    @GetMapping("/project/{projectId}")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<List<FundingDto>> getFundingsByProject(@PathVariable Long projectId) {
        List<FundingDto> fundings = fundingService.getFundingsByProject(projectId);
        return ResponseEntity.ok(fundings);
    }

    /**
     * 获取当前用户的经费记录
     */
    @GetMapping("/user")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<List<FundingDto>> getUserFundings(Authentication authentication) {
        List<FundingDto> fundings = fundingService.getUserFundings(authentication.getName());
        return ResponseEntity.ok(fundings);
    }

    /**
     * 获取经费统计信息
     */
    @GetMapping("/stats")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<FundingStatsDto> getFundingStats() {
        FundingStatsDto stats = fundingService.getFundingStats();
        return ResponseEntity.ok(stats);
    }

    /**
     * 更新经费记录
     */
    @PutMapping("/{id}")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<FundingDto> updateFunding(@PathVariable Long id, @Valid @RequestBody UpdateFundingRequest request, Authentication authentication) {
        FundingDto updatedFunding = fundingService.updateFunding(id, request, authentication.getName());
        return ResponseEntity.ok(updatedFunding);
    }

    /**
     * 审批经费记录
     */
    @PostMapping("/{id}/approve")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<FundingDto> approveFunding(@PathVariable Long id, @RequestBody Map<String, Boolean> payload, Authentication authentication) {
        boolean approved = payload.getOrDefault("approved", false);
        FundingDto approvedFunding = fundingService.approveFunding(id, approved, authentication.getName());
        return ResponseEntity.ok(approvedFunding);
    }

    /**
     * 删除经费记录
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<MessageResponse> deleteFunding(@PathVariable Long id, Authentication authentication) {
        fundingService.deleteFunding(id, authentication.getName());
        return ResponseEntity.ok(new MessageResponse("经费记录删除成功"));
    }
}